<template lang="pug">
.parameters
  .parameters__top
    .parameters__top__left
      mt-button(v-for="item in buttonLeftList" 
        :key="item.label"
        v-bind="item")
    .parameters__top_right
      mt-button(v-for="item in buttonRightList" 
          :key="item.label"
          v-bind="item")
  .parameters__bottom
    .parameters__bottom__left
      SectionTitle(padding="0 8px" style="margin-bottom: var(--mt-margin);") 计算机信息
      mt-form(:model="editingObj")
        el-row(
          :gutter="16"
        )
          mt-form-item(
            v-for="item of items"
            :key="item.label"
            :prop="item.label"
            v-bind="item"
            label-width ="100px"
          )
    .parameters__bottom__right
      SectionTitle(padding="0 8px" style="margin-bottom: var(--mt-margin);") 通讯信息
      mt-form(:model="editingObj" v-if="editingObj?.portType == 1||editingObj?.portType == 2||editingObj?.portType == 3||editingObj?.portType == 6")
        el-row(
            :gutter="16"
          )
            mt-form-item(
              v-for="item of rows"
              :key="item.label"
              :prop="item.label"
              v-bind="item"
              label-width ="100px"
            )
      mt-table(v-bind="tableProps" v-if="editingObj?.portType==4||editingObj?.portType==5||editingObj?.portType==7")
logModel(v-model="logShow" :selectEquipment="props.selectEquipment") 
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  useNotify,
  Select,
  type IAction,
  type TableProps,
} from "@scmt/common-components";
import { useApi } from "@scmt/core-api";

import { type EquipmentEntity } from "@scmt/api-lis-equipment";
import { SectionTitle } from "@scmt/common-components";
import type { CommunicationParametersEntity } from "@scmt/api-lis-communication-parameters";
import { useRequest } from "@scmt/common-hooks";
import logModel from "./logModel.vue";

const $api = useApi();
const $notify = useNotify();
const editingObj = ref<null | CommunicationParametersEntity>({});
const logShow = ref(false);

//添加 Props属性
const props = defineProps({
  selectEquipment: {
    type: Object as PropType<EquipmentEntity>,
    default: () => {},
  },
});

const tableData = ref([{ patientName: "", tubeId: "" }]);

const tableProps = computed(() => {
  const tableProps: TableProps = {
    data: tableData.value,
    columns: [
      {
        prop: "patientName",
        label: "参数名称",
        render: (params) => {
          return h(
            "div",
            {
              style: {
                display: "flex",
              },
            },
            h(Select, {
              style: {
                padding: "4px",
              },
              modelValue: params.row.patientName,
              "onUpdate:modelValue": (val: string) => {
                params.row.patientName = val;
              },
              options: $api.dict.item.listAsOptions("parameter_name"),
            })
          );
        },
      },
      {
        prop: "tubeId",
        label: "参数值",
        render: (params) => {
          return h(
            "div",
            {
              style: {
                display: "flex",
              },
            },
            h(resolveComponent("mt-input"), {
              style: {
                width: "100%",
                padding: "4px",
              },
              modelValue: params.row.tubeId,
              "onUpdate:modelValue": (val: string) => {
                params.row.tubeId = val;
              },
            })
          );
        },
      },
      {
        label: "操作",
        actions: [
          { event: "addCownward", label: "向下添加", type: "danger" },
          { event: "delete", label: "删除", type: "danger" },
        ],
      },
    ],
    onAct: onPageActions,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "addCownward":
      tableData.value.push({ patientName: "", tubeId: "" });
      break;
  }
};

const { request, data, loadingMap } = useRequest({
  get: (val: string) => {
    return $api.lis.communicationParameters
      .getCommunicationParametersByDeviceId(val)
      .then((data) => {
        editingObj.value = editingObj.value =
          $api.lis.communicationParameters.$$createEntity(data);
      });
  },
  openServer: (val: string) => {
    return $api.lis.equipment.openServer(val).then(() => {
      $notify.success("打开服务器成功");
    });
  },
  closeServer: (val: string) => {
    return $api.lis.equipment.closeServer(val).then(() => {
      $notify.success("关闭服务器成功");
    });
  },
  save: async (model: CommunicationParametersEntity) => {
    return $api.lis.communicationParameters.save(model).then(() => {
      $notify.success("保存成功");
    });
  },
});

const buttonLeftList = computed(() => {
  return [
    {
      event: "save",
      label: "保存",
      type: "primary",
      loading: loadingMap.save,
      onClick: () => {
        request(
          "save",
          Object.assign({}, editingObj.value, {
            deviceId: props.selectEquipment?.id,
          })
        );
      },
    },
    {
      event: "relation",
      label: "取消",
      type: "primary",
    },
    {
      event: "relation",
      label: "解析设置",
      type: "primary",
    },
  ];
});

const buttonRightList = computed(() => {
  return [
    {
      event: "relation",
      label: "刷新",
      type: "primary",
      disabled: true,
      onClick: () => {},
    },
    {
      event: "relation",
      label: "停止",
      type: "primary",
      loading: loadingMap.closeServer,
      disabled: !Boolean(props.selectEquipment?.id),
      onClick: () => {
        request("closeServer", props.selectEquipment?.id ?? "");
      },
      visible: Boolean(props.selectEquipment?.isStartServer == 1),
    },
    {
      event: "relation",
      label: "启用",
      type: "primary",
      loading: loadingMap.openServer,
      disabled: !Boolean(props.selectEquipment?.id),
      onClick: () => {
        request("openServer", props.selectEquipment?.id ?? "");
      },
      visible: !Boolean(props.selectEquipment?.isStartServer == 1),
    },
    {
      event: "relation",
      label: "查看日志",
      type: "primary",
      disabled: !Boolean(props.selectEquipment?.id),
      onClick: () => {
        logShow.value = true;
      },
    },
  ].filter((i) => i.visible === void 0 || i.visible);
});

const items = computed<FormItemProps[]>(() => [
  {
    prop: "computerName",
    label: "电脑名称",
    span: 24,
  },
  {
    prop: "bindAddress",
    label: "绑定地址",
    span: 24,
    options: {
      type: "textarea",
      rows: 4,
    },
  },
  {
    prop: "portType",
    label: "端口类型",
    span: 24,
    as: "select",
    options: {
      loadMethod: () => $api.dict.item.listAsOptions("port_type"),
    },
  },
  {
    prop: "serialPortNumber",
    label: "串口号",
    span: 24,
    as: "select",
    visible: editingObj.value?.portType == 1,
    options: {
      loadMethod: () => $api.dict.item.listAsOptions("serial_port_number"),
    },
  },
]);
const rows = computed<FormItemProps[]>(() =>
  [
    {
      prop: "localNumber",
      label: "本地端口号",
      span: 24,
      visible:
        editingObj.value?.portType == 2 ||
        editingObj.value?.portType == 3 ||
        editingObj.value?.portType == 6,
    },
    {
      prop: "serverIp",
      label: "服务器IP",
      span: 24,
      visible:
        editingObj.value?.portType == 2 ||
        editingObj.value?.portType == 3 ||
        editingObj.value?.portType == 6,
    },
    {
      prop: "baudRate",
      label: "波特率",
      span: 12,
      as: "select",
      visible: editingObj.value?.portType == 1,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("baud_rate"),
      },
    },
    {
      prop: "dataBits",
      label: "数据位",
      span: 12,
      as: "select",
      visible: editingObj.value?.portType == 1,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("data_bits"),
      },
    },
    {
      prop: "inspectionMethod",
      label: "校验方法",
      span: 12,
      as: "select",
      visible: editingObj.value?.portType == 1,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("verification_method"),
      },
    },
    {
      prop: "urinalysis",
      label: "工作小组",
      span: 12,
      visible: editingObj.value?.portType == 1,
    },
    {
      prop: "stopPosition",
      label: "停止位",
      span: 12,
      as: "select",
      visible: editingObj.value?.portType == 1,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("stop_position"),
      },
    },
    {
      prop: "endCode",
      label: "结束码",
      span: 12,
      visible: editingObj.value?.portType == 1,
    },
    {
      prop: "analysisMethod",
      label: "解析方式",
      span: 12,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("analysis_method"),
      },
    },
    {
      prop: "analysisMode",
      label: "解析方法",
      span: 12,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("analysis_mode"),
      },
    },
    {
      prop: "startLogo",
      label: "开始标志",
      span: 12,
    },
    {
      prop: "endFlag",
      label: "结束标志",
      span: 12,
    },
    {
      prop: "startLogo",
      label: "解析应答",
      span: 12,
    },
    {
      prop: "analyzeDataType",
      label: "解析数据类型",
      span: 12,
      as: "select",
      visible: editingObj.value?.portType == 1,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("analyze_data_types"),
      },
    },
    {
      prop: "transmissionMode",
      label: "传输方式",
      span: 12,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("transmission_mode"),
      },
    },
    {
      prop: "communicationResponseType",
      label: "通讯应答类型",
      span: 12,
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("analyze_data_types"),
      },
    },
    {
      prop: "communicationInquiryCode",
      label: "通讯询问码",
      span: 12,
    },
    {
      prop: "communicationResponseCode",
      label: "通讯应答码",
      span: 12,
    },
    {
      prop: "communicationEndCode",
      label: "通讯结束码",
      span: 12,
    },
    {
      prop: "delayTransmissionTime",
      label: "延迟传输时间",
      span: 12,
    },
    {
      prop: "flowControlSymbol",
      label: "流控制符",
      span: 12,
      as: "select",
      visible: editingObj.value?.portType == 1,
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("flow_control_symbol"),
      },
    },
  ].filter((i) => i.visible === void 0 || i.visible)
);

watch(
  () => props.selectEquipment,
  (item) => {
    if (item && item.id) {
      request("get", item.id);
    } else {
      editingObj.value = $api.lis.communicationParameters.$$createEntity({});
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped>
.parameters {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: var(--mt-padding);

  &__top {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
  }

  &__bottom {
    margin-top: var(--mt-margin);
    flex: 9;
    display: flex;
    width: 100%;
    :deep(.el-form-item__label) {
      font-weight: 500 !important;
    }
    &__left {
      flex: 3;
    }
    &__right {
      margin-left: var(--mt-margin);
      flex: 6;
    }
  }
}
</style>
